factorial <-function(n) { result <-1if (n >1) {for (i in2:n) { result <- result * i } }return(result)}# Calling the functionnumber <-5cat(number, "factorial is", factorial(number))
5 factorial is 120
Object-oriented
setClass("Circle",slots =list(radius ="numeric"))Circle <-function(radius) {new("Circle", radius = radius)}# Define a generic function for areasetGeneric("area", function(x) standardGeneric("area"))
[1] "area"
# Define the method for calculating the area of a CirclesetMethod("area", "Circle", function(x) { pi *slot(x, "radius")^2})# Define a generic function for circumferencesetGeneric("circumference", function(x) standardGeneric("circumference"))
[1] "circumference"
# Define the method for calculating the circumference of a CirclesetMethod("circumference", "Circle", function(x) {2* pi *slot(x, "radius")})# Create a Circle objectcircle <-Circle(5)cat("The area of the circle is", area(circle), "\n")
The area of the circle is 78.53982
cat("The circumference of the circle is", circumference(circle))
The circumference of the circle is 31.41593
Functional programming
# Functional Programming Example: Using purrr to operate on lists# Load purrr for functional programminglibrary(purrr)# A list of numbersnumbers <-list(1, 2, 3, 4, 5)# Define a function to square a numbersquare <-function(x) {return(x^2)}# Use map to apply the square function to each element of the listsquared_numbers <-map(numbers, square)# Print the resultcat("Squared numbers:", unlist(squared_numbers))